package com.kexun.platform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kexun.model.Gd;
import com.kexun.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

public class QQMusic {
    private static Logger logger = Logger.getLogger("com.kexun");
    private String filePath;

    private static ExecutorService executorService = Executors.newFixedThreadPool(3);

    public void setFilePath(String filePath) {

        this.filePath = filePath;
    }

    public QQMusic(String filePath) {
        this.filePath = filePath;
    }

    public QQMusic() {
    }


    public void startKeyWord(String[] keyWords) {
        executorService.execute(() -> {
            for (String keyWord : keyWords) {
                System.out.println("开始下载关键字为" + keyWord);
                JSONArray songList = getKeyWordSongList(keyWord.trim());
                if (songList == null) {
                    return;
                }
                for (int i = 0; i < songList.size(); i++) {
                    JSONObject data = songList.getJSONObject(i);
                    download(data, SOURCE.关键字);
                }
            }
        });
    }


    public void startTop(int[] topIds) {
        System.out.println("开始下载排行榜");
        executorService.execute(() -> {
            for (int topId : topIds) {
                JSONArray topList = getTopList(topId);
                if (topList == null) {
                    return;
                }
                for (int i = 0; i < topList.size(); i++) {
                    JSONObject songData = topList.getJSONObject(i);
                    download(songData, SOURCE.排行榜);
                }
            }
        });
    }

    public void startMusicList() {
        System.out.println("开始下热门歌单");
        executorService.execute(() -> {
            List<Gd> hotGdList = getHotGdList();
            for (Gd gd : hotGdList) {
                String tid = gd.getTid();
                JSONArray musicList = getMusicListByGd(tid);
                for (int i = 0; i < musicList.size(); i++) {
                    JSONObject data = musicList.getJSONObject(i);
                    download(data, SOURCE.热门歌单);
                }
            }
        });
    }


    private void download(JSONObject data, SOURCE source) {
        ModelAdapter.MusicModel musicModel = new ModelAdapter(data, source.getType()).create();
        String singer = musicModel.getSinger();
        String songmid = musicModel.getSongmid();
        String albumname = musicModel.getAlbumname();
        String songname = musicModel.getSongname();
        Integer albumid = musicModel.getAlbumid();
        Integer interval = musicModel.getInterval();
        String name = songname + "-" + singer;
        String playUrl = getPlayUrl(songmid);
        if (playUrl == null || playUrl == "") {
            System.err.println("下载失败无法获取到播放地址: " + name);
            return;
        }

        String fileName = name + ".m4a";
        boolean b = saveData(playUrl, fileName, source.getName());
        if (b) {
            System.out.println("下载成功: " + name);
        } else {
            System.err.println("下载失败: " + name);
        }
    }


    //关键字搜索下载
    private JSONArray getKeyWordSongList(String keyword) {
        String searchUrl = QQConfig.getSearch(keyword);
        String searchRes = HttpUtils.doGet(searchUrl);
        String resStr = searchRes.substring(searchRes.indexOf("(") + 1, searchRes.lastIndexOf(")"));
        JSONArray list = JSON.parseObject(resStr).getJSONObject("data").getJSONObject("song").getJSONArray("list");
        return list;
    }

    //排行榜id下载
    private JSONArray getTopList(int topId) {
        String phbUrl = QQConfig.getPhb(topId);
        String phbRes = HttpUtils.doGet(phbUrl);
        JSONObject jsonObject = JSON.parseObject(phbRes);
        JSONArray songlist = jsonObject.getJSONArray("songlist");
        return songlist;
    }


    //获取热门歌单的列表
    private List<Gd> getHotGdList() {
        //请求改成List
        String url = "https://u.y.qq.com/cgi-bin/musics.fcg?_=1596358835945&sign=zza0t8mc0qwtmfgsr8ca4c62c1677aa33520233f0d9ccce41";
        String req = "{\"req_0\":{\"method\":\"get_playlist_by_tag\",\"param\":{\"id\":10000000,\"sin\":0,\"size\":60,\"order\":5,\"is_parent\":0},\"module\":\"playlist.PlayListPlazaServer\"},\"req_1\":{\"method\":\"get_category_grid\",\"module\":\"playlist.PlayListNavigateServer\",\"param\":{}},\"comm\":{\"g_tk\":2013812016,\"uin\":\"1813723783\",\"format\":\"json\",\"ct\":20,\"cv\":1773,\"platform\":\"wk_v17\"}}";

        String s = HttpUtils.doPostJson(url, req);
        ArrayList<Gd> gdList = new ArrayList<>();
        JSONObject jsonObject = JSON.parseObject(s);
        JSONArray v_playlist = jsonObject.getJSONObject("req_0").getJSONObject("data").getJSONArray("v_playlist");
        for (int i = 0; i < v_playlist.size(); i++) {
            JSONObject item = v_playlist.getJSONObject(i);
            Gd gd = new Gd();
            gd.setTitle(item.getString("title"));
            gd.setTid(item.getString("tid"));
            gd.setImage_url(item.getString("cover_url_big").replace("\\", ""));
            gdList.add(gd);
        }
        return gdList;
        // System.out.println(s);
    }


    private JSONArray getMusicListByGd(String tid) {
        String url = "https://c.y.qq.com/v8/fcg-bin/fcg_v8_playlist_cp.fcg?_=1596357870619&uin=1813723783&format=json&inCharset=utf-8&outCharset=utf-8&notice=0&needNewCode=1&cv=1773&ct=20&newsong=1&id=" + tid;
        String s = HttpUtils.doGet(url);
        JSONObject jsonObject = JSON.parseObject(s);
        return jsonObject.getJSONObject("data").getJSONArray("cdlist").getJSONObject(0).getJSONArray("songlist");
    }

    private String getPlayUrl(String songmid) {
        String purl = getVkey(songmid);
        if (StringUtils.isEmpty(purl)) {
            return null;
        }
        String qplayUrl = "http://220.170.89.153/amobile.music.tc.qq.com/" + purl;
        return qplayUrl;
    }

    private String getVkey(String songmid) {
        String data = "{\"req\":{\"module\":\"vkey.GetVkeyServer\",\"method\":\"CgiGetVkey\",\"param\":{\"guid\":\"9879159010\",\"songmid\":[\"" + songmid + "\"],\"songtype\":[0],\"uin\":\"1813723783\",\"loginflag\": 1,\"platform\": \"20\"}}}";
        try {
            data = URLEncoder.encode(data, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "https://u.y.qq.com/cgi-bin/musicu.fcg?g_tk=1621061997&format=json&platform=yqq&data=" + data;
        String s = HttpUtils.doGet(url);
        JSONObject jsonObject = JSON.parseObject(s);
        JSONObject req = jsonObject.getJSONObject("req");
        JSONObject data1 = req.getJSONObject("data");
        JSONObject midurlinfo = data1.getJSONArray("midurlinfo").getJSONObject(0);
        String purl = midurlinfo.getString("purl");
        return purl;
    }

    private boolean saveData(String downloadUrl, String fileName, String sourceName) {
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(120 * 1000);
            conn.setInstanceFollowRedirects(false);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            int responseCode = conn.getResponseCode();

            if (responseCode != 200) {
                if (responseCode == 302) {
                    String location = conn.getHeaderField("Location");
                    return saveData(location, fileName, sourceName);
                }
                return false;
            }
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);
            File sourceFile = new File(filePath + "/" + sourceName);
            if (!sourceFile.exists()) {
                sourceFile.mkdir();
            }

            //文件保存位置
            File file = new File(filePath + "/" + sourceName + "/" + fileName);

            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        //二进制
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();

    }
}
